package com.zhangjk.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class BeanNotNullUtil {

	public static final String STRING = "class java.lang.String";
	public static final String INTEGER = "class java.lang.Integer";
	public static final String SHORT = "class java.lang.Short";
	public static final String LONG = "class java.lang.Long";

	public static void init(Object model) throws NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		Field[] field = model.getClass().getDeclaredFields();
		for (int j = 0; j < field.length; j++) { // 遍历所有属性
			if (!Modifier.isStatic(field[j].getModifiers())) {
				String name = field[j].getName(); // 获取属性的名字
				field[j].setAccessible(true);
				name = name.substring(0, 1).toUpperCase() + name.substring(1);// 将属性的首字符大写，方便构造
				String type = field[j].getGenericType().toString(); // 获取属性的类型

				Method getter = model.getClass().getMethod("get" + name);
				Method setter = null;
				if (STRING.equals(type)) {
					String value = (String) getter.invoke(model); // 调用getter方法获取属性值
					if (value == null || value.trim().equals("")) {
						value = "";
						setter = model.getClass().getMethod("set" + name, value.getClass());
						setter.invoke(model, value);// 调用setter方法赋值
					}
				} else if (INTEGER.equals(type)) {
					Integer value = (Integer) getter.invoke(model);
					if (value == null) {
						value = 0;
						setter = model.getClass().getMethod("set" + name, value.getClass());
						setter.invoke(model, value);
					}
				} else if (SHORT.equals(type)) {
					Short value = (Short) getter.invoke(model);
					if (value == null) {
						value = (short) 0;
						setter = model.getClass().getMethod("set" + name, value.getClass());
						setter.invoke(model, value);
					}
				} else if (LONG.equals(type)) {
					Long value = (Long) getter.invoke(model);
					if (value == null) {
						value = 0l;
						setter = model.getClass().getMethod("set" + name, value.getClass());// setter
																							// 由于带参数必须
																							// 设置params的class
						setter.invoke(model, value);
					}
				}
			}
		}
	}
}
